<?	/*
	// File:	login.inc.php
	// Purpose:	web-cp login screen, handle logout
	// Creation:	2001-10-29
	// Author:	Felix <webmaster@can-host.com>
	*/
//
// Check if needed vars are there
if (!isset($cfg))
	return 'login.inc.php :: $cfg not loaded (web/config.inc.phps)';
if (!is_array($T)) {
	include("lang/".$cfg['defaultlang'].".phps");
	// Check for and include local language file
	$tmplang = explode("/",__FILE__);
	array_pop($tmplang);array_pop($tmplang);
	$tmplang = implode("/",$tmplang)."/lang.php";
	if (file_exists($tmplang))
		include($tmplang);
}
if (!isset($web_name))
	return 'login.inc.php :: $web_name not loaded (web/init.inc.phps)';
// Check if variables have been sent with POST, if so get them into variables.
$username = load_input_vars('username');
list($username, $userdomain) = explode('@', $username, 2);
$password = load_input_vars('password');
$timeout = load_input_vars('timeout');
$md5pass = load_input_vars('md5pass');
$salt = load_input_vars('salt');
//
// If fetch method is a POST (attempted login), verify its authenticity
if (!empty($_POST) AND $data['failed'] != "recover") {

	// Standardize Input
	$username = trim($username);

	if (!eregi($rx['user'],$data['username']))
		$data['username'] = '_invalid';

	if (!$cfg['ssl']) {
		$salt = floor(time() / 300);
		$password = trim($md5pass);
	} else {
		$password = md5(trim($password));
		$salt = '';
	}
	// get remote IP address
	$ip = get_remote_ip();

	// Check for failed logins within the last 24 hrs from this IP
	$fl = mysql_query("SELECT count(id) as FailCount FROM log WHERE remote_ip = \"$ip\" AND log_msg = \"login failed\" AND time > DATE_SUB(NOW(), INTERVAL 1 DAY)");
	$fldata = mysql_fetch_array($fl);
	if ($fldata['FailCount'] < 15 && $fldata['FailCount'] > 2) {
		sleep($fldata['FailCount']);
	} elseif ($fldata['FailCount'] >= 15)  {
		$password = "";
	}

	// translate domain to ID
	$res = mysql_query('SELECT `id` FROM `domains` WHERE domain = "'.$userdomain.'" AND type="domain" LIMIT 1') or print(mysql_error());
	list($domainid) = mysql_fetch_row($res);

	// Check user against database
	$dbp = mysql_query("SELECT type,favorites,skin,lang,DECODE(password,'".$cfg['key']."') AS password FROM users WHERE username='$username' AND id = '$domainid'") or print(mysql_error());
	$data = mysql_fetch_array($dbp);

	if (md5($data['password'].$salt) != $password) {
		unset($data);
	}

	// If User / Password not valid
	if (!$data) {
		// Check if username is valid & log if appropriate (warn)
		$dbp = mysql_query("SELECT username FROM users WHERE username='".$username."' AND id = '$domainid'");
		if (mysql_num_rows($dbp))
			webcp_log(1,"",$username." ($domainid)","login failed",$_SERVER['REMOTE_ADDR']);
		// Stay in login and display error message
		$data['failed'] = "invalid";
	}
	// If sysname doesn't match
	elseif (!check_sysname()) {
		// Log invalid sysname / ip address
		webcp_log(1,"","Invalid IP Address/System Name (".$cfg['sysname'].")","login failed",$_SERVER['REMOTE_ADDR']);
		// Stay in login and display wrong sysname error
		$data['failed'] = "sysname";

	}
	// If the user is valid and server ip/sysname is valid
	else {
		// Log it
		webcp_log(2,"",$username." ($domainid)","login successful",$_SERVER['REMOTE_ADDR']);

		// If user is a demo, associate current webcp_tag (if it exists, else pass on)
		switch ($data['type']) {

			case 'demo':
			$dbp = mysql_query("SELECT webcp_tag FROM users WHERE username='$username' AND id = '$domainid'");
			$data2 = mysql_fetch_array($dbp);
			if (trim($data2['webcp_tag'])) {
				$webcp_tag = $data2['webcp_tag'];
				break;
			}
			default:

			// Generate Unique Tag & Update the db
			srand((float) microtime() * 1000000);
			do {
				$webcp_tag = md5(uniqid(rand()));
				$dbp = mysql_query("SELECT username FROM users WHERE webcp_tag='$webcp_tag'");
			} while (mysql_num_rows($dbp));
			mysql_query("UPDATE users SET webcp_tag='$webcp_tag', remote_addr='".$_SERVER['REMOTE_ADDR']."', timeout='".(time() + $timeout)."' WHERE username='$username' AND id = '$domainid'");
		}
		// if 'cookiesec' is set, set cookies with ssl and sysname settings.  Else don't.
		if(strstr($_SERVER['SERVER_NAME'],":")){
			$server_server_name=explode(":",$_SERVER['SERVER_NAME']);
			$server_server_name=$server_server_name[0];
		}else $server_server_name=$_SERVER['SERVER_NAME'];
                if(strstr($cfg['sysname'],":")){
                        $cfg_sysname=explode(":",$cfg['sysname']);
			$cfg_sysname=$cfg_sysname[0];
                }else $cfg_sysname=$cfg['sysname'];
                if ($server_server_name != "") $cfg_sysname=$server_server_name;
                elseif ($_SERVER['SERVER_ADDR'] != "") $cfg_sysname=$_SERVER['SERVER_ADDR'];

		if ($cfg['cookiesec']) {
			if (!send_cookie("skin",$data['skin'],time()+5000000,"",$cfg_sysname, $cfg['ssl']?1:0)) { echo 'Cookie failed.'; return; }
			if (!send_cookie("lang",$data['lang'],time()+5000000,"",$cfg_sysname, $cfg['ssl']?1:0)) { echo 'Cookie failed.'; return; }
			if (!send_cookie("webcp_tag",$webcp_tag,time()+5000000,"",$cfg_sysname, $cfg['ssl']?1:0)) { echo 'Cookie failed.'; return; }
		} else {
			if (!send_cookie("skin",$data['skin'],time()+5000000,"",$_SERVER['HTTP_HOST'])) { echo 'Cookie failed.'; return; }
			if (!send_cookie("lang",$data['lang'],time()+5000000,"",$_SERVER['HTTP_HOST'])) { echo 'Cookie failed.'; return; }
			if (!send_cookie("webcp_tag",$webcp_tag,time()+5000000,"",$_SERVER['HTTP_HOST'])) { echo 'Cookie failed.'; return; }
		}

		// If 'bookmark' is set, redirect user to the correct location
		if (trim($data['favorites']) AND !trim($cp)) {
			$tmp = explode(":",$data['favorites']);
			$cp = $tmp[0];
			$url = $tmp[1];
			$number = $tmp[2];
			$user =  $tmp[3];
		}
		send_header("Location: ".$web_name."/?cp=$cp&url=$url&number=$number&user=$user&".time()."&tag=$webcp_tag");
		return false;
	}
}
// If $data['failed'] is a logout, unset the cookie, clear the tag & timeout.
if ($data['failed'] == "logout" OR $data['failed'] == "access") {
	// if 'cookiesec' is set, unset cookie with ssl and domain settings.  Else don't.
	if ($cfg['cookiesec'])
		send_cookie("webcp_tag","",time() - 3600,"/",$cfg['sysname']);
	else
		send_cookie("webcp_tag","",time() - 3600,"/",$_SERVER['HTTP_HOST']);

	// update database
	mysql_query("UPDATE users SET webcp_tag='', timeout='' WHERE webcp_tag='$webcp_tag'");
}
// If $data['failed'] is a su (substitute user), verify user level, unset the cookie, re-login.
elseif ($data['failed'] == "su") {
	$dbp = mysql_query("SELECT id,level FROM users WHERE webcp_tag='$webcp_tag'");
	$tmpdata = mysql_fetch_array($dbp);

	// only preset password if current user is server admin+
	if ($tmpdata['id'] AND $tmpdata['level'] <= 1) {
		$tmpdata = fetchdata("password", "user", array($username, $domainid));
		$password = $tmpdata['password'];
	}
	// if 'cookiesec' is set, unset cookie with ssl and domain settings.  Else don't.
	if ($cfg['cookiesec'])
		send_cookie("webcp_tag","",time() - 3600,"/",$cfg['sysname']);
	else
		send_cookie("webcp_tag","",time() - 3600,"/",$_SERVER['HTTP_HOST']);

	// update database
	mysql_query("UPDATE users SET webcp_tag='', timeout='' WHERE webcp_tag='$webcp_tag'");
}
// If $data['failed'] is a recover, e-mail the user's password to the domain admin's e-mail address
elseif ($data['failed'] == "recover") {
	/*
	// Standardize Input
	$username = trim($username);

	// Check user against database
	$userdata = fetchdata("id,password","user", array($username, $domainid));
	// If the user is valid
	if ($userdata) {
		$domain = fetchdata("email","domain",$userdata['id']);
		if ($domain) {
			$msg = strtr(array(
				'{date}' => date($T['date_time_format']),
				'{ip}' => get_remote_ip(),
				'{password}' => $userdata['password'],
				), $T['Pass Recovery Msg']);
			mail($domain['email'],"web-cp ".$T['Password Recovery']." -- ".$username, $msg, "From: <".$cfg['adminmail'].">\n");
		} else {
			$data['failed'] = "recover-failed";
		}
	}
	else
		$data['failed'] = "recover-failed";
		*/
}


// Check if its a case of initializing:  The server configuration hasn't been created yet
if (!file_exists($cfg['basedir'].'/config.php')/* || !$cfg['programslocated'] || !$cfg['serversselected'] || !$cfg['modulesselected']*/) {
	// Start first phase of setup (setup_config.php)
	echo "<h3>web-cp Setup</h3>";
	echo "<p>web-cp is not currently installed. Please use the following link to start setup. <a href='setup_config.php'>Setup web-cp</a></p>";
	echo "<p>Please note you will need to have server details such as <b>Fully Qualified Hostname</b> and <b>DNS Server</b> addresses ready to install web-cp. You must also ensure that you have started the web-cp server daemon program - webcp.php before Setup can begin. Please refer to <a href='http://www.web-cp.net'>www.web-cp.net</a> for installation advice and support enquiries.</p>";
	
 	return false;
}
/*
// Check if its a case of initializing:  The webcp database hasn't been created yet
$dbp = mysql_query("SHOW TABLES FROM ".$cfg['dbname']);
if (!mysql_num_rows($dbp) && !file_exists($cfg['basedir'].'/config.php')) {
 	send_header("Location: ".$web_name."/setup_config.php");
 	return false;
}
*/
// Check if its a case of initializing:  There are no users in the users table
$dbp = @mysql_query("SELECT username FROM users LIMIT 1");
if (!@mysql_num_rows($dbp)) {
	send_header("Location: ".$web_name."/setup.php");
	return false;
}

// Show login screen
?>
<div align="center"><br>
	<?
		// If $data['failed'] is set (failed login), echo the error
		if (isset($data['failed'])) {
			echo "<p><center><font color='#990000'>";
			echo $T['err']['login'][$data['failed']];
			echo "</font></center></p>\n";
		}

		// set salt for md5 (5 minute 'timer' to login)
		$utime = floor(time() / 300);
	?>
	<form name="webcplogin" action="<?="./?cp=$cp&url=$url&number=$number&user=$user"; ?>" method="POST" onSubmit="submitonce(this); <? if (!$cfg['ssl']) echo "md5crypt('webcplogin','password','md5pass',$utime);" ?>">
	<table border="0" cellspacing="0" cellpadding="0" class="tblbg" width="300">
	<tr><td align="right">
	<table border="0"  cellspacing="1" width="100%" cellpadding="1" >
	<tr>
		<td class="tbltop"><b>web-cp <?=$cfg['webcp'];?>&nbsp;&nbsp;&nbsp;&nbsp;<?=$T['Login'];?></b></td>
	</tr>
	<tr>
		<td valign="top" >
		<table width="100%" border="0" cellspacing="0" cellpadding="0" class="content">
		<tr>
			<td align="right"><font size="1">
			<br>
			<div style="font-size:14px;"><?=$T['Username'];?>&nbsp;</div>
			<input type="text" name="username" size="35" maxlength="40" value="<? if ($username) echo $username.'@'.$userdomain;?>">&nbsp;<br>
			<div style="font-size:14px;"><?=$T['Password'];?>&nbsp;</div>
			<input type="password" name="password" size="35" maxlength="40" value="">&nbsp;<br><br>
			<div style="font-size:14px;"><?=$T['Timeout'];?>&nbsp;</div>
			<select name="timeout">
				<option value="3600"> <?=$T['1 Hour'];?>
				<option value="86400"> <?=$T['1 Day'];?>
				<option value="604800"> <?=$T['1 Week'];?>
				<option value="2592000"> <?=$T['1 Month'];?>
			</select>
			</td>
		</tr>
		</table>
		</td>
	</tr>
	</table>
	</td>
	</tr>
	</table>
	<input type="hidden" value="" name="md5pass">
	<div style="width: 300px;" style="font-size:10px;" align="center">
	<?=$cfg['sysname'];?>
	<p align="right"><input type="submit" value="<?=$T['Login'];?>"></p>
	</div>
	</form>
	<br><br>

	<div style="font-size:10px;">
	<?=$T['login note'];?>
	</div>

<br><br>

<div style="padding: 0px; border: 0px; margin: 0px; line-height: 14px; font-size: 12px;">

<a href="?url=passwd">&nbsp&nbsp&nbsp <?=$T['lost password'];?> &nbsp&nbsp&nbsp</a>

</div>

</div>
